<template>
	<div class="padding-container device-wrap">
    <div class="title-part">
      <el-button size="mini" type="primary" class="pull-right" @click="toExport()">{{ $root.lang.control.device.detail.app.logs.export }}</el-button>
      <el-button size="mini" type="primary" class="lang-select  pull-right" @click="toHistory()">{{ $root.lang.control.device.detail.app.logs.history }}</el-button>
      <el-button size="mini" type="warning" class="pull-right" @click="toEmpty()">{{ $root.lang.control.device.detail.app.logs.empty }}</el-button>
      <el-button size="mini" class="pull-right" @click="toDo(0)">{{ $root.lang.control.device.detail.app.logs.stop }}</el-button>
      <el-button size="mini" type="primary" class="pull-right" @click="toDo(1)">{{ $root.lang.control.device.detail.app.logs.query }}</el-button>
		</div>
    <div class="box">
      <div v-for="(log, index) in logs" :key="index">
        <div v-html="log" class="item"></div>
      </div>
    </div>
     <LogSetting :show="showLogSetting" :appId="appId + ''" :deviceId="deviceId + ''" @editReceive="getReceive" />
	</div>
</template>

<script>
import '@/options/baseState'
import LogSetting from './logSetting'

import mqtt from 'mqtt'
export default {
	name: 'DeviceAppLog',
  components: {
    LogSetting
  },
	data() {
		return {
			connection: {
        host: 'emq.joshvm.com',
        port: 443,
        endpoint: '/mqtt',
        options: {
          clean: true, // 保留会话
          connectTimeout: 4000, // 超时时间
          reconnectPeriod: 4000, // 重连时间间隔
          // 认证信息
          clientId: '',
          username: 'app-log-web',
        }
      },
      subscription: {
        topic: null,
        qos: 0,
      },
      publication: {
        topic: '',
        qos: 0,
        payload: '',
      },
      client: {
        connected: false,
      },
      params: {
        imei: null,
        appIdentification: null,
        appV: null,
        applicationVendor: null,
      },
      logs: [],
      showLogSetting: false,
      appId: null,
      deviceId: null,
      uniqueId: '',
		}
	},
  methods: {
    createConnection() {
      // 连接字符串, 通过协议指定使用的连接方式
      // ws 未加密 WebSocket 连接
      // wss 加密 WebSocket 连接
      // mqtt 未加密 TCP 连接
      // mqtts 加密 TCP 连接
      // wxs 微信小程序连接
      // alis 支付宝小程序连接
      const { host, port, endpoint, options } = this.connection
      const connectUrl = `wss://${host}:${port}${endpoint}`
      // console.log(connectUrl)
      try {
        this.client = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('connect error', error)
      }
      this.client.on('connect', () => {
        console.log('connected')
        this.doSubscribe()
      })
      this.client.on('error', error => {
        console.log('connect failed', error)
      })
      // 断开发起重连
      this.client.on('reconnect', error => {
        console.log('reconnect', error)
      })
      this.client.on('message', (topic, message) => {
        if(topic == this.subscription.topic ) {
          var str = String(message)
          this.logs.push(str)
        }
      })
    },
    doSubscribe() {
      this.subscription.topic = this.params.imei + '/' 
      + this.params.appIdentification + '/' + this.params.applicationVendor + '/' 
      + this.params.appV + '/log'
      const { topic, qos } = this.subscription
      this.client.subscribe(topic, qos, (error, res) => {
        if (error) {
          console.log('subscribe to topics error', error)
          return
        }
        // console.log('Subscribe to topics', topic)
      })
    },
    doUnSubscribe() {
      const { topic } = this.subscription
      this.client.unsubscribe(topic, error => {
        if (error) {
          console.log('unsubscribe error', error)
        }
      })
    },
    doPublish() {
      const { topic, qos, payload } = this.publication
      this.client.publish(topic, payload, qos, error => {
        if (error) {
          console.log('publish error', error)
        } else {
          console.log(`publish ${payload} to topic ${topic}`)
        }
      })
    },
    connect() {
      this.connection.options.clientId = String(new Date().getTime())
      this.createConnection()
    },
    disconnect() {
      if(this.client.connected) {
        try {
          this.client.end()
          this.client = {
            connected: false,
          }
          console.log('successfully disconnected')
        } catch (error) {
          console.log('disconnect failed', error.toString())
        }
      }
    },
    toDo(type) {
      let url = '/daliy/real-time/query'
      let tip = this.$root.lang.control.device.detail.app.logs.queryTip
      if(type == 0) {
        url = '/daliy/real-time/stop'
        tip = this.$root.lang.control.device.detail.app.logs.stopTip
      }
      this.request({
        url: url,
        method: 'post',
        data: this.$root.optionProcess(this.params)
      }).then(response => {
        this.$message({
          message: tip,
          type: 'success',
          duration: 3 * 1000
        })
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toEmpty() {
      this.logs = []
    },
    scrollToBottom() {
      this.$nextTick(()=>{
        let box = this.$el.querySelector(".box")
        box.scrollTop = box.scrollHeight
      })
    },
    toHistory() {
      this.showLogSetting = true
      this.appId = this.$route.query.a
      this.deviceId = this.$route.query.d
    },
    getReceive(data) {
      this[data.key] = data.value
    },
    toExport(index, row) {
      if(this.uniqueId == '') {
        this.$message({
          message: this.$root.lang.control.device.detail.app.logs.historyErrorTip,
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      this.$confirm(this.$root.lang.confirm.exportLog, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.exportImmediately,
        cancelButtonText: this.$root.lang.confirm.noExport,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.request({
          url: '/daliy/history/export?uniqueId=' + this.uniqueId,
          method: 'get',
          responseType: "blob"
        }).then(response => {
          loading.close()
          if(response.data.type == 'application/json') {
            this.$message({
              message: this.$root.lang.control.device.detail.app.logs.noHistoryTip,
              type: 'error',
              duration: 3 * 1000
            })
            return
          }
          // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          let blob = new Blob([response.data], {type: response.data.type});
          // 创建一个a标签
          const link = document.createElement('a')
          // 设置a标签的下载属性
          link.download = this.uniqueId + '.log';
          // 将a标签设置为隐藏
          link.style.display = 'none';
          // 把之前处理好的地址赋给a标签的href
          link.href = URL.createObjectURL(blob);
          // 将a标签添加到body中
          document.body.appendChild(link);
          // 执行a标签的点击方法
          link.click();
          // 下载完成释放URL对象
          URL.revokeObjectURL(link.href)
          // 移除a标签
          document.body.removeChild(link)
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {
        
      })
    },
  },
  created() {
    this.params.imei = this.$route.query.m
    this.params.appIdentification = this.$route.query.i
    this.params.appV = this.$route.query.v
    this.params.applicationVendor = this.$route.query.e
    this.connect()
  },
  destroyed() {
    this.disconnect()
  },
  mounted() {
    this.scrollToBottom()
	},
  updated(){
    this.scrollToBottom()
  },
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.padding-container {
		text-align:left;
		.title-part {
			text-align: left;
			font-size: 18px;
			padding-bottom: 40px;
		}
    .lang-select {
      margin-right: 10px;
      cursor: pointer;
    }
    .box {
      border: 1px solid #ebeef5; 
      // border: 1px solid #000; 
      height: calc(75vh); //视窗高度的75%
      padding: 10px; 
      overflow: auto;
    }
    .item {
      margin-bottom: 5px; 
      font: 14px "consolas","arial","SimSun","Microsoft Yahei";
      color: #606266
    }
	}
</style>